package io.socket;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * TCP 服务器
 * 参考：https://www.runoob.com/java/java-networking.html
 * @author ben
 * @date 2021-11-01 20:51:13 CST
 */
public class Server1 extends Thread {

	private ServerSocket serverSocket = null;
	
	public Server1(int port) throws IOException {
		this.serverSocket = new ServerSocket(port);
		this.serverSocket.setSoTimeout(60000);
	}
	
	@Override
	public void run() {
		while (true) {
			try {
				System.out.println("等待远程连接，端口号为：" + serverSocket.getLocalPort() + "...");
				Socket server = serverSocket.accept();
				
				// socket会一直存在吗？
				Thread nt = new Thread(()->{
					try {
						while (true) {
							System.out.println("循环：远程主机地址：" + server.getRemoteSocketAddress() + 
									", 远程端口：" + server.getPort());
							
							DataInputStream dis = new DataInputStream(server.getInputStream());
							String instr = dis.readUTF();
							System.out.println(instr);
							
							DataOutputStream dos = new DataOutputStream(server.getOutputStream());
							dos.writeUTF("谢谢连接我：" + server.getLocalSocketAddress() + "\nGoodbye!");
							
							if ("end".equals(instr)) {
								server.close();
							}
						}
					} catch (IOException e) {
						e.printStackTrace();
					}
				});
				nt.start();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	public static void main(String[] args) {
		try {
			System.out.println("建立TCP服务器：");
			Server1 s1 = new Server1(10000);
			
			//  怎么不是 start()? TODO
			System.out.println("s1.run()...");
			s1.run();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
